Audio Player

The AVPlayer class provides audio and video playback capabilities with support for playback control, looping, event callbacks, and metadata retrieval. You can use setSource() to set a media source (either a local file or a remote URL) and call play() to start playback.


Getting Started

Example usage of AVPlayer:

1const player = new AVPlayer()
2
3// Set the media source (local file or remote URL)
4if (player.setSource("https://example.com/audio.mp3")) {
5    player.onReadyToPlay = () => {
6        player.play()
7    }
8    player.onEnded = () => {
9        console.log("Playback finished.")
10    }
11} else {
12    console.error("Failed to set media source.")
13}

API Reference

Properties

volume: number

Controls the playback volume, ranging from 0.0 (muted) to 1.0 (maximum).

1player.volume = 0.5 // Set to 50% volume

duration: DurationInSeconds

The total duration of the media in seconds. This value will be 0 until the media is fully loaded.

1console.log(`Media duration: ${player.duration} seconds`)

currentTime: DurationInSeconds

The current playback time in seconds. You can set this value to seek to a specific time.

1player.currentTime = 30 // Seek to 30 seconds

rate: number

Controls the playback speed. A value of 1.0 is normal speed; values below 1.0 slow down playback, and values above 1.0 speed it up.

1player.rate = 1.5 // Play at 1.5× speed

timeControlStatus: TimeControlStatus

Indicates the current playback state. Possible values:

  • paused: playback is paused
  • waitingToPlayAtSpecifiedRate: waiting for conditions to start (e.g., buffering)
  • playing: currently playing

numberOfLoops: number

Sets how many times the media will loop.

  • 0: no looping
  • positive value: specific number of loops
  • negative value: infinite looping
1player.numberOfLoops = -1 // Infinite looping

Methods

setSource(filePathOrURL: string): boolean

Sets the media source for playback. Accepts a local file path or a remote URL.

Returns:

  • true if successfully set
  • false if setting failed

play(): boolean

Starts playback of the current media.

Returns:

  • true if playback started successfully
  • false if it failed to start

pause()

Pauses the current playback.


stop()

Stops playback and resets the position to the beginning.


dispose()

Releases all player resources and removes observers. Call this method when the player is no longer needed to avoid memory leaks.


loadMetadata(): Promise<AVMetadataItem[] | null>

Loads detailed metadata for the current media file.

Returns:

  • An array of AVMetadataItem objects
  • null if no metadata is available or no source has been set

Example:

1const metadata = await player.loadMetadata()
2if (metadata) {
3  for (const item of metadata) {
4    console.log(item.key, await item.stringValue)
5  }
6}

loadCommonMetadata(): Promise<AVMetadataItem[] | null>

Loads the common metadata of the current media, where each AVMetadataItem provides a commonKey that can be used across media formats.

Example:

1const commonMetadata = await player.loadCommonMetadata()
2if (commonMetadata) {
3  const titleItem = commonMetadata.find(i => i.commonKey === "title")
4  console.log("Title:", await titleItem?.stringValue)
5}

Callbacks

onReadyToPlay?: () => void

Called when the media is ready for playback.


onTimeControlStatusChanged?: (status: TimeControlStatus) => void

Called when the playback state changes, such as from “waiting” to “playing.”


onEnded?: () => void

Called when playback finishes.


onError?: (message: string) => void

Called when an error occurs during playback. Receives an error message as an argument.


Audio Session Handling

AVPlayer relies on the system’s shared audio session. You can configure it using SharedAudioSession to ensure correct playback behavior.

1await SharedAudioSession.setCategory('playback', ['mixWithOthers'])
2await SharedAudioSession.setActive(true)

Handling interruptions (such as phone calls):

1SharedAudioSession.addInterruptionListener((type) => {
2  if (type === 'began') player.pause()
3  else if (type === 'ended') player.play()
4})

Common Use Cases

Play Remote Audio

1player.setSource("https://example.com/audio.mp3")
2player.onReadyToPlay = () => player.play()

Play Local File

1player.setSource("/path/to/audio.mp3")
2player.play()

Loop Playback

1player.numberOfLoops = 3 // Loop 3 times
2player.play()

Retrieve Metadata

1const metadata = await player.loadCommonMetadata()
2if (metadata) {
3  const artist = metadata.find(i => i.commonKey === "artist")
4  console.log("Artist:", await artist?.stringValue)
5}

Best Practices

  1. Resource Management Always call dispose() after playback to release system resources.

  2. Error Handling Implement the onError callback to handle playback issues gracefully (e.g., network failures).

  3. Interruption Management Use audio session interruption listeners to pause and resume playback smoothly.

  4. UI State Updates Use onTimeControlStatusChanged to update your UI when the playback state changes.

  5. Metadata Usage Use loadCommonMetadata() to retrieve general information such as title, artist, or album artwork for display in your app’s UI.


Full Example

1const player = new AVPlayer()
2
3await SharedAudioSession.setCategory('playback', ['mixWithOthers'])
4await SharedAudioSession.setActive(true)
5
6if (player.setSource("https://example.com/audio.mp3")) {
7  player.onReadyToPlay = () => player.play()
8  player.onEnded = () => {
9    console.log("Playback finished")
10    player.dispose()
11  }
12  player.onError = (message) => {
13    console.error("Playback error:", message)
14    player.dispose()
15  }
16
17  // Load metadata
18  const commonMetadata = await player.loadCommonMetadata()
19  if (commonMetadata) {
20    const titleItem = commonMetadata.find(i => i.commonKey === "title")
21    console.log("Title:", await titleItem?.stringValue)
22  }
23} else {
24  console.error("Failed to set media source")
25}